#include "ConcordePreparer.h"

ConcordePreparer::ConcordePreparer()
{

}

ConcordePreparer::~ConcordePreparer()
{
}

void ConcordePreparer::prepare(string outputLocation, WaypointDB& waypointDB)
{
	vector<string> cols, rows;
	waypointDB.getAllRows(cols, rows);

	string id, name, description, latitude, longitude;
	bool addRow = false;

	int pos = 0;
	for (std::vector<string>::iterator it = rows.begin(); it != rows.end(); ++it, pos++)
	{
		switch (pos)
		{
		case 0: // ID column
			id = *it;
			break;
		case 1: // name column
			name = *it;
			break;
		case 2: // desc column
			description = *it;
			break;
		case 3: // latitude column
			latitude = *it;
			break;
		case 4: // longitude column (also end of row)
			longitude = *it;
			addRow = true;
			break;
		}

		if (addRow)
		{
			ConcordeWaypoint concordeWaypoint(id, name, description, latitude, longitude);

			concordeWaypoints.push_back(concordeWaypoint);

			addRow = false;
			pos = -1; // have to set the position below 0
		}
	}

	writeFile(outputLocation);

}

void ConcordePreparer::writeFile(const string& outputFile)
{
	ofstream tspFile(outputFile.c_str());

	tspFile << "NAME : " << outputFile << endl;
	tspFile << "TYPE : TSP" << endl;
	tspFile << "EDGE_WEIGHT_TYPE: GEOM" << endl;
	tspFile << "DIMENSION: " << concordeWaypoints.size() << endl;
	tspFile << "COMMENT : =======" << endl;
	tspFile << "COMMENT : Generated Concorde TSP file by WaypointHandler program" << endl;
	tspFile << "COMMENT : =======" << endl;

	for (std::vector<ConcordeWaypoint>::iterator it = concordeWaypoints.begin(); it != concordeWaypoints.end(); ++it)
	{
		tspFile << "COMMENT : " << it->getCacheName() << " - " << it->getCacheDesc(false) << endl;
	}

	tspFile << "NODE_COORD_SECTION" << endl;

	for (std::vector<ConcordeWaypoint>::iterator it = concordeWaypoints.begin(); it != concordeWaypoints.end(); ++it)
	{
		tspFile << it->getSequence() << " " << it->getLatitude() << " " << it->getLongitude() << endl;
	}

	tspFile.close();

}
